package com.wugh.fast.module.mapper;

import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;

import java.util.LinkedList;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * 说明: 动态Schema村存储
 *
 * @author wugh
 * @date 2018-12-03 08:52
 */
public class DynamicSchemaStorage {
    private static ThreadLocal<LinkedList<String>> schemaStorage = new InheritableThreadLocal<LinkedList<String>>() {
        /**
         * Child threads should get a copy of the parent's hashmap.
         */
        @Override
        protected LinkedList<String> childValue(LinkedList<String> parentValue) {
            if (parentValue == null) {
                return null;
            } else {
                return new LinkedList<>(parentValue);
            }
        }
    };

    /**
     * 清空线程池的schema存储
     */
    public static void clear() {
        schemaStorage.remove();
    }

    /**
     * 设置schema
     *
     * @param schema
     */
    public static void set(String schema) {
        LinkedList<String> list = Lists.newLinkedList();
        list.add(schema);
        schemaStorage.set(list);
    }

    /**
     * 获取schema
     *
     * @return
     */
    public static String get() {
        LinkedList<String> schemas = schemaStorage.get();
        if (schemas == null) {
            schemaStorage.set(new LinkedList<>());
        }
        if (CollectionUtils.isEmpty(schemas)) {
            return null;
        }
        return schemas.getLast();
    }

    /**
     * 临时切换schema
     *
     * @param schema
     * @param consumer
     */
    public static void templateSwitch(String schema, Consumer<String> consumer) {
        templateSwitch(schema, (t) -> {
            consumer.accept(t);
            return null;
        });
    }

    /**
     * 临时切换schema
     *
     * @param schema
     * @param function
     */
    public static <T> T templateSwitch(String schema, Function<String, T> function) {
        LinkedList<String> list = schemaStorage.get();
        if (list == null) {
            list = Lists.newLinkedList();
            schemaStorage.set(list);
        }
        list.add(schema);
        try {
            return function.apply(schema);
        } finally {
            list.removeLast();
        }
    }
}
